package com.eclink.iot.tcpserver.controller;

import com.eclink.iot.rfid.RFIDDevice;
import com.eclink.iot.rfid.RFIDDeviceClient;
import com.eclink.iot.rfid.RFIDServer;
import com.eclink.iot.tcpserver.RFIDServerManager;
import com.eclink.iot.tcpserver.domain.dto.DeviceDTO;
import com.eclink.iot.tcpserver.domain.dto.DeviceSocketDTO;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.net.Socket;
import java.net.SocketAddress;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("rfid")
public class RFIDController {

    @GetMapping("list")
    public Collection<DeviceDTO> getDeviceList() {
        Collection<RFIDDevice> devices = RFIDServerManager.getOnlineDevices();
        List<DeviceDTO> res = new ArrayList<>();
        for(RFIDDevice device : devices) {
            DeviceDTO deviceDTO = new DeviceDTO();
            BeanUtils.copyProperties(device, deviceDTO);
            Set<RFIDDeviceClient> clientList = device.getClientList();
            for(RFIDDeviceClient client : clientList) {
                DeviceSocketDTO socketDTO = new DeviceSocketDTO();
                Socket socket = client.getSocket();
                SocketAddress address = socket.getRemoteSocketAddress();
                socketDTO.setConnected(socket.isConnected());
                if (address != null) {
                    socketDTO.setAddress(address.toString());
                }
                deviceDTO.getSocketList().add(socketDTO);
            }
            res.add(deviceDTO);
        }
        return res;
    }

    @GetMapping("getStatus/{uuid}")
    public Integer getStatus(@PathVariable String uuid) {
        if (RFIDServerManager.isDeviceActive(uuid)) {
            return 1;
        }
        return 0;
    }

    @PutMapping("inventory/{uuid}")
    public Integer inventory(@PathVariable String uuid) {
        RFIDServerManager.inventory(uuid);
        return 0;
    }

    @PutMapping("stopInventory/{uuid}")
    public Integer stopInventory(@PathVariable String uuid) {
        RFIDServerManager.stopInventory();
        return 0;
    }

}
